package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbDict;
import com.bwie.service.TbDictService;
import com.bwie.mapper.TbDictMapper;
import com.bwie.utils.R;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
* @author Lenovo
* @description 针对表【tb_dict(字典表)】的数据库操作Service实现
* @createDate 2025-06-24 15:23:44
*/
@Service
public class TbDictServiceImpl extends ServiceImpl<TbDictMapper, TbDict>
    implements TbDictService{

    @Autowired
    private TbDictMapper tbDictMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostConstruct
    public void loadDictList(){
        System.out.println("项目启动时，加载字典列表到缓存中");

        List<TbDict> tbDictList = tbDictMapper.selectList(null);
        for (TbDict tbDict : tbDictList) {
            String key1="dict-"+tbDict.getDictType();
            String key2=tbDict.getDictId()+"";
            redisTemplate.opsForHash().put(key1,key2, JSON.toJSONString(tbDict));
        }
        System.out.println("字典加载完成");
    }

    @Override
    public R getDictList(Integer typeId) {

        String key="dict-"+typeId;
        Boolean aBoolean = redisTemplate.hasKey(key);
        if (aBoolean){
            List<Object> objectList = redisTemplate.opsForHash().values(key);

            ArrayList<TbDict> dicts = new ArrayList<>();
            for (Object object : objectList) {
                TbDict tbDict = JSON.parseObject(object.toString(), TbDict.class);
                dicts.add(tbDict);
            }
        }

        List<TbDict> tbDictList = tbDictMapper.selectList(new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, typeId));
        for (TbDict tbDict : tbDictList) {
            String key1="dict-"+tbDict.getDictType();
            String key2=tbDict.getDictId()+"";
            redisTemplate.opsForHash().put(key1,key2, JSON.toJSONString(tbDict));
        }

        return R.ok().setData(tbDictList);


    }
}




